package com.sell.controller;

import com.sell.exceptions.ResultEnum;
import com.sell.exceptions.SellException;
import lombok.extern.slf4j.Slf4j;
import me.chanjar.weixin.common.api.WxConsts;
import me.chanjar.weixin.common.exception.WxErrorException;
import me.chanjar.weixin.mp.api.WxMpService;
import me.chanjar.weixin.mp.bean.result.WxMpOAuth2AccessToken;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;

import java.net.URLEncoder;

/**
 * @Author: megan
 * @Data: 2018/12/9 7:58 PM
 * @Description: 微信sdk: https://github.com/wechat-group/weixin-java-tools
 */
@Controller
@RequestMapping("/wechat")
@Slf4j
public class WechatController {

    @Autowired
    private WxMpService wxMpService;

    /**
     * 构造网页授权url<br/>
     * 注意： 微信后台配置的redirect_url 前缀不能填写 https 或者 http
     * 如： 你的回调域名为 www.baidu.com 你不能填写 http://www.baidu.com
     *
     * @param returnUrl
     */
    @GetMapping("/authorize")
    public String authorize(@RequestParam("returnUrl") String returnUrl) {
        // 这是 natapp 内网穿透地址,正式上线可以配置一下，换成线上回调域名
        String url = "http://755fc9e00c511c66.natapp.cc";
        String redirectUrl = wxMpService.oauth2buildAuthorizationUrl(url + "/sell/wechat/userInfo", WxConsts.OAUTH2_SCOPE_USER_INFO, URLEncoder.encode(returnUrl));
        log.info("[微信网页授权] 获取code，result={}", redirectUrl);

        return "redirect:" + redirectUrl;
    }

    /**
     * 获取微信用户信息openId
     *
     * @param code
     * @param redirectUrl
     */
    @GetMapping("/userInfo")
    public String userInfo(@RequestParam("code") String code,
                           @RequestParam("state") String redirectUrl) {
        WxMpOAuth2AccessToken wxMpOAuth2AccessToken;
        try {
            wxMpOAuth2AccessToken = wxMpService.oauth2getAccessToken(code);
        } catch (WxErrorException e) {
            log.error("[微信网页授权] : {}", e);
            throw new SellException(ResultEnum.WX_MP_ERROR.getCode(), e.getError().getErrorMsg());
        }
        String openId = wxMpOAuth2AccessToken.getOpenId();

        return "redirect:" + redirectUrl + "?openid=" + openId;
    }
}
